import inspect
from django.contrib import admin
from . import models, DjangoModelAdmin
from django.forms.models import model_to_dict

for attr in dir(models):
    model = getattr(models, attr)
    if not inspect.isclass(model):
        continue

    try:
        field_names = list(model_to_dict(model()).keys())
        # print("field_names", field_names)
        # print("field_names", field_names)
        admin.site.register(model, DjangoModelAdmin(field_names))
    except Exception as e:  # noqa
        # print(e)
       
        pass

import copy
import datetime
import random
import string


def copy_item(modeladmin, request, queryset):
    '''
    管理后台快捷复制数据
    :param modeladmin:
    :param request:
    :param queryset:
    :return:
    '''
    if not queryset.exists():
        return
    data = queryset.values()[0]
    del data['id']
    _data = copy.deepcopy(data)
    for k, v in data.items():
        if isinstance(data[k], datetime.date):
            # _data = data
            _data[k] += datetime.timedelta(days=-1)
            continue
        else:
            try:
                _data[k] = v + '_' + random.choice(string.digits + string.ascii_lowercase + string.ascii_uppercase)
            except Exception:
                if '_id' in k:
                    continue
                try:
                    _data[k] += 1
                except Exception:
                    pass
                pass

    queryset.create(**_data)


copy_item.short_description = "copy item"

admin.site.add_action(copy_item)  # 管理后台快捷复制数据
